import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException {
        String filePath = "idcard.jpg";
        URL realUrl = new URL("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=24.82e29e326ff3cd44e87aa098f8b19507.2592000.1490850945.282335-9320197");
        HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        String body = String.format("id_card_side=front&image=%s", new BASE64Encoder().encode(readImage(filePath)).replaceAll("\n", ""));
        connection.getOutputStream().write(body.getBytes("UTF-8"));
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        String result = "";
        while ((line = in.readLine()) != null) {
            result += line;
        }
        System.out.println(result);
    }

    public static byte[] readImage(String filePath){
        File file = new File(filePath);
        byte[] content = new byte[new Long(file.length()).intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(content);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}
